define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'province/index'+location.search,
                  //  import_url: 'schooldata/import',
                    table: 'collegial',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('省份ID'), sortable: true},
                      //  {field: 'province_id', title: '省份ID', operate: 'LIKE'},
                        {field: 'name', title: '省份', operate: 'LIKE'},
                        {field: 'full_name', title: '省份全程', operate: 'LIKE'},
                        {field: 'proid', title: '行政区划代码', operate: 'LIKE'},
                        {field: 'sort', title: '权重', operate: false},
                        {field: 'city_num', title: '市区个数', operate: false},
                        {field: 'region_num', title: '县级个数', operate: false},
                        {field: 'operate', title: __('Operate'), table: table, buttons: [
                                {
                                    name: 'city',
                                    text: __('配置省份市区'),
                                    title:  __('配置省份市区'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-addtabs',
                                    icon: 'fa fa-eye',
                                    url: 'province/city?province_id={id}',
                                    // extend:'data-area=["60%","70%"]',
                                    callback: function (data) {
                                    },
                                },
                                //  {name: 'send', text: __('view'), icon: 'fa fa-eye', classname: 'btn btn-xs btn-warning btn-dialog chakan', url: 'member/collegial/collegial_detail'},
                            ],  events: Table.api.events.operate, formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                $(table).data("operate-edit", true); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                $(table).data("operate-del", null); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }},
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        city: function () {
            // 初始化表格参数配置
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'province/city'+location.search,
                    add_url: 'province/add_city?province_id='+Config.pid,
                    edit_url: 'province/edit_city',
                    del_url: 'province/del_city',
                    table: 'collegial',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('市区ID'), sortable: true},
                        //  {field: 'province_id', title: '省份ID', operate: 'LIKE'},
                        {field: 'province', title: '省份', operate: false},
                        {field: 'city', title: '市区', operate: 'LIKE'},
                        {field: 'region_num', title: '县级个数', operate: false},
                        {
                            field: 'update_time',
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            title: __('更新时间'),
                            formatter: Table.api.formatter.datetime
                        },
                        {field: 'admin.nickname', title: '操作人', operate: 'LIKE'},
                        {field: 'operate', title: __('Operate'), table: table, buttons: [
                                {
                                    name: 'region',
                                    text: __('配置县级'),
                                    title:  __('配置县级'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-addtabs',
                                    icon: 'fa fa-eye',
                                    url: 'province/region?city_id={id}',
                                    // extend:'data-area=["60%","70%"]',
                                    callback: function (data) {
                                    },
                                },
                                //  {name: 'send', text: __('view'), icon: 'fa fa-eye', classname: 'btn btn-xs btn-warning btn-dialog chakan', url: 'member/collegial/collegial_detail'},
                            ],  events: Table.api.events.operate, formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                $(table).data("operate-edit", true); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                $(table).data("operate-del", true); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }},
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        region: function () {
            // 初始化表格参数配置
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'province/region'+location.search,
                    add_url: 'province/add_region?city_id='+Config.pid,
                    edit_url: 'province/edit_region',
                    del_url: 'province/del_region',
                    table: 'collegial',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('县ID'), sortable: true},
                        //  {field: 'province_id', title: '省份ID', operate: 'LIKE'},
                        {field: 'province', title: '省份', operate: false},
                        {field: 'city', title: '市区', operate: 'LIKE'},
                        {field: 'region', title: '县区', operate: 'LIKE'},
                        {
                            field: 'update_time',
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            title: __('更新时间'),
                            formatter: Table.api.formatter.datetime
                        },
                        {field: 'admin.nickname', title: '操作人', operate: 'LIKE'},
                        {field: 'operate', title: __('Operate'), table: table,events: Table.api.events.operate, formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                $(table).data("operate-edit", true); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                $(table).data("operate-del", true); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }},
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        log: function () {
            // 初始化表格参数配置
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'schooldata/log',
                  //  import_url: 'schooldata/import',
                    table: 'collegial',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'school_id', title: '院校ID', operate: 'LIKE'},
                        {field: 'school.school', title: '院校名称', operate: 'LIKE'},
                        {field: 'log', title: '修改记录', operate: 'LIKE'},

                     //   {field: 'email', title:'邮箱',operate: false},
                      //  {field: 'address', title:'地址',operate: false},
                        {
                            field: 'log',
                            title: __('地址'),
                            operate: false,
                            formatter : function(value, row, index, field){
                                return "<span style='display: block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;' title='" + row.log + "'>" + value + "</span>";
                            },
                            cellStyle : function(value, row, index, field){
                                return {
                                    css: {
                                        "white-space": "nowrap",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width":"150px"
                                    }
                                };
                            }
                        },
                    ]
                ]
            });
            table.on('load-success.bs.table', function (e, data) {
                console.log(data);
                //这里可以获取从服务端获取的JSON数据
                // console.log(data);
                //这里我们手动设置底部的值
                $("#num").text(data.total);
                $("#certification_total").text(data.certification_total);
            });
            $(document).on("click", ".province", function () {

                $(this).parent().children().find('li').removeClass('show');
                $(this).children().eq(0).addClass('show');
                var pid=$(this).attr('data-pid');
                var opt = {
                    url: 'extend/university/collegial?pid='+pid ,//这里可以包装你的参数
                };
                $('#table').bootstrapTable('refresh', opt)
            });
            $(document).on("click", ".register", function () {

                Backend.api.addtabs('extend/users','注册情况');
            });
            $(document).on("click", ".certification", function () {
                Backend.api.addtabs('cms/school/school_bind','认证情况');
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add_city: function () {
            Controller.api.bindevent();
        },
        edit_city: function () {
            Controller.api.bindevent();
        },
        edit_region: function () {
            Controller.api.bindevent();
        },
        add_region: function () {
            Controller.api.bindevent();
        },

        cs_vue: function() {
            function debounce(handle, delay) {
                let time = null;
                return function() {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function() {
                        handle.apply(self, arg);
                    }, delay)
                }
            }
            var storeinventoryIndex = new Vue({
                el: "#storeinventoryIndex",
                data() {
                    return {
                        productCode: '',
                        productID: '',
                        phone: '',
                        productName: '',
                        storeinventoryDataTemp: [],
                        storeinventoryData: [],
                        multipleSelection: [],
                        chooseType: 0,
                        activityType: 'all',
                        activeStatus: 'all',
                        searchKey: '',
                        priceFrist: '',
                        priceLast: '',
                        preheattime: '',
                        sort: 'id',
                        order: 'desc',
                        offset: 0,
                        limit: 10,
                        totalPage: 0,
                        currentPage: 1,
                        rowDel: false,
                        allDel: false,

                        upStatus: true,
                        allAjax: true,
                        tableAjax: false
                    }
                },
                created() {
                    this.getData();
                },
                methods: {
                    checkSelectable(row) {
                        return this.searchForm.status == 0 || this.searchForm.status == 1 ?
                            true : false
                    },
                    handleChange(file, fileList) {
                        console.log('file', file)
                        console.log('file', fileList)
                        this.ajaxUpload(file)
                    },
                    //导入点击事件
                    upLoadFile() {
                        this.$refs['upload'].$refs['upload-inner'].handleClick()
                    },
                    fileChange(){
                        let resultFile = document.getElementById('DRMD').files[0];
                        const formData = new FormData();
                        formData.append('file', resultFile)
                        $.ajax({
                            type: "post",
                            url: `${Config.moduleurl}/shopro/storeinventory/storeinventory/upexport`,
                            data: formData,
                            cache: false,
                            processData: false,
                            contentType: false,
                            success: function(data) {
                                if (data.code === 1) {
                                    Toastr.success(data.msg);
                                    that.detailForm[id] = data.data.url
                                    window.location.reload();
                                } else {
                                    Toastr.error(data.msg);
                                    window.location.reload();
                                    // that.$notify({
                                    // 	title: '警告',
                                    // 	message: data.msg,
                                    // 	type: 'warning'
                                    // });
                                }
                            }
                        })
                        // 下方调接口
                    },
                    // 导出
                    exportApply() {
                        let that = this;
                        let filter = {}
                        let op = {}
                        for (key in that.searchForm) {
                            if (key == 'status' || key == 'apply_type') {
                                if (that.searchForm[key] !== '' && that.searchForm[key] !=
                                    'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            } else if (key == 'form_1_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_1_key] = that.searchForm[key];
                                }
                            } else if (key == 'createtime' || key == 'updatetime') {
                                if (that.searchForm[key]) {
                                    if (that.searchForm[key].length > 0) {
                                        filter[key] = that.searchForm[key].join(' - ');
                                    }
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        window.location.href =
                            `${Config.moduleurl}/shopro/storeinventory/storeinventory/export?filter=${JSON.stringify(filter)}&op=${JSON.stringify(op)}&offset=${that.offset}&limit=${that.limit}&type=2`;
                    },
                    ajaxUpload(file) {
                        console.log(file)
                        let that = this;
                        var formData = new FormData();
                        formData.append("file", file);
                        console.log(formData)
                        // formData.append("file", $('#' + id)[0].files[0]);
                        $.ajax({
                            type: "post",
                            url: `${Config.moduleurl}/shopro/storeinventory/storeinventory/upexport`,
                            data: formData,
                            cache: false,
                            processData: false,
                            contentType: false,
                            success: function(data) {
                                if (data.code == 1) {
                                    that.detailForm[id] = data.data.url
                                } else {
                                    that.$notify({
                                        title: '警告',
                                        message: data.msg,
                                        type: 'warning'
                                    });
                                }
                            }
                        })
                    },
                    getData() {
                        let that = this;
                        if (!that.allAjax) {
                            that.tableAjax = true;
                        }
                        let dataAc = {
                            search: that.searchKey,
                            status: that.activeStatus,
                            activity_type: that.activityType,
                            min_price: that.priceFrist,
                            max_price: that.priceLast,
                            offset: that.offset,
                            limit: that.limit,
                            sort: that.sort,
                            order: that.order,
                            productCode:that.productCode,
                            productID:that.productID,
                            phone:that.phone,
                            productName:that.productName,
                            offset: that.offset,
                            limit: that.limit,
                        };
                        if (that.activityType == 'score') {
                            dataAc = {
                                search: that.searchKey,
                                status: that.activeStatus,
                                app_type: that.activityType,
                                min_price: that.priceFrist,
                                max_price: that.priceLast,
                                offset: that.offset,
                                limit: that.limit,
                                sort: that.sort,
                                order: that.order,
                            };
                        }
                        Fast.api.ajax({
                            url: 'shopro/storeinventory/storeinventory',
                            loading: false,
                            type: 'GET',
                            data: dataAc
                        }, function(ret, res) {
                            console.log('库存', res.data.rows)
                            that.storeinventoryData = res.data.rows;

                            that.totalPage = res.data.total;
                            that.allAjax = false;
                            that.tableAjax = false;
                            return false;
                        }, function(ret, res) {
                            that.allAjax = false;
                            that.tableAjax = false;
                        })
                    },
                    tabOpt(tab, event) {
                        this.activeStatus = tab.name
                    },
                    goodsOpt(type, id) {
                        let that = this;
                        switch (type) {
                            // case 'create':
                            // 	Fast.api.open('shopro/goods/goods/add', '新增商品', {
                            // 		callback() {
                            // 			that.getData();
                            // 		}
                            // 	})
                            // 	break;
                            case 'edit':
                                Fast.api.open('shopro/goods/goods/edit/ids/' + id + "?id=" +
                                    id + "&type=edit", '编辑商品', {
                                    callback() {
                                        that.getData();
                                    }
                                })
                                break;
                            // case 'down':
                            // 	let idArr = []
                            // 	if (that.multipleSelection.length > 0) {
                            // 		that.multipleSelection.forEach(i => {
                            // 			idArr.push(i.id)
                            // 		})
                            // 		let idss = idArr.join(',')
                            // 		that.editStatus(idss, 'down')
                            // 	}
                            // 	break;
                            // case 'up':
                            // 	let idArrup = []
                            // 	if (that.multipleSelection.length > 0) {
                            // 		that.multipleSelection.forEach(i => {
                            // 			idArrup.push(i.id)
                            // 		})
                            // 		let idup = idArrup.join(',')
                            // 		that.editStatus(idup, 'up')
                            // 	}
                            // 	break;
                            // case 'del':
                            // 	let ids;
                            // 	if (id) {
                            // 		ids = id;
                            // 	} else {
                            // 		let idArr = []
                            // 		if (that.multipleSelection.length > 0) {
                            // 			that.multipleSelection.forEach(i => {
                            // 				idArr.push(i.id)
                            // 			})
                            // 			ids = idArr.join(',')
                            // 		}
                            // 	}
                            // 	if (ids) {
                            // 		that.$confirm('此操作将删除商品, 是否继续?', '提示', {
                            // 			confirmButtonText: '确定',
                            // 			cancelButtonText: '取消',
                            // 			type: 'warning'
                            // 		}).then(() => {
                            // 			Fast.api.ajax({
                            // 				url: 'shopro/goods/goods/del/ids/' +
                            // 					ids,
                            // 				loading: true,
                            // 				type: 'POST',
                            // 			}, function(ret, res) {
                            // 				that.getData();
                            // 				return false;
                            // 			})
                            // 		}).catch(() => {
                            // 			that.$message({
                            // 				type: 'info',
                            // 				message: '已取消删除'
                            // 			});
                            // 		});
                            // 	}
                            // 	break;
                            // case 'copy':
                            // 	Fast.api.open('shopro/goods/goods/edit/ids/' + id + "?id=" +
                            // 		id + "&type=copy", '商品详情', {
                            // 			callback() {
                            // 				that.getData();
                            // 			}
                            // 		})
                            // 	break;
                            case 'filter':
                                that.offset = 0;
                                that.limit = 10;
                                that.currentPage = 1;
                                that.getData();
                                break;
                            case 'clear':
                                that.productCode=''
                                that.productID=''
                                that.phone=''
                                that.productName=''
                                that.offset = 0;
                                that.limit = 10;
                                that.currentPage = 1;
                                that.getData();
                                break;
                            // case 'recycle':
                            // 	Fast.api.open('shopro/goods/goods/recyclebin', '查看回收站')
                            // 	break;
                            // default:
                            // 	Fast.api.open('shopro/goods/goods/edit/ids/' + type.id +
                            // 		"?id=" + type.id + "&type=edit", '编辑商品', {
                            // 			callback() {
                            // 				that.getData();
                            // 			}
                            // 		})
                            // 	break;
                        }
                    },
                    hideup() {
                        for (key in this.selectedRowId) {
                            this.selectedRowId[key] = false;
                        }
                    },
                    sortOrder(sort, order) {
                        this.sort = sort;
                        this.order = order;
                        this.getData();
                    },
                    handleSelectionChange(val) {
                        this.multipleSelection = val;
                    },
                    handleSizeChange(val) {
                        this.offset = 0
                        this.limit = val;
                        this.currentPage = 1;
                        this.getData()
                    },
                    handleCurrentChange(val) {
                        this.currentPage = val;
                        this.offset = (val - 1) * this.limit;
                        this.getData()
                    },
                    editStatus(id, type) {
                        let that = this;
                        Fast.api.ajax({
                            url: `shopro/goods/goods/setStatus/ids/${id}/status/${type}`,
                            loading: true,
                        }, function(ret, res) {
                            that.getData();
                            return false;
                        })
                    },
                    chooseOpt(type) {
                        this.activityType = type
                    },
                    isShoose() {
                        this.chooseType == 0 ? 1 : 0;
                        if (this.chooseType == 0) {
                            this.activityType = 'all';
                            this.priceFrist = "";
                            this.priceLast = "";
                        }
                    },
                    tableRowClassName({
                                          rowIndex
                                      }) {
                        if (rowIndex % 2 == 1) {
                            return 'bg-color';
                        }
                        return '';
                    },
                    tableCellClassName({
                                           columnIndex
                                       }) {
                        if (columnIndex == 2) {
                            return 'cell-left';
                        }
                        return '';
                    },
                    debounceFilter: debounce(function() {
                        this.getData()
                    }, 1000),
                },
                watch: {
                    activeStatus(newVal, oldVal) {
                        if (newVal != oldVal) {
                            this.offset = 0;
                            this.limit = 10;
                            this.currentPage = 1;
                            this.getData();
                        }
                    },
                    searchKey(newVal, oldVal) {
                        if (newVal != oldVal) {
                            this.offset = 0;
                            this.limit = 10;
                            this.currentPage = 1;
                            this.debounceFilter();
                        }
                    },
                },
            })
        },

        api: {
            formatter: {
                content: function (value, row, index) {
                    var extend = this.extend;
                    if (!value) {
                        return '';
                    }
                    var valueArr = value.toString().split(/,/);
                    var result = [];
                    $.each(valueArr, function (i, j) {
                        result.push(typeof extend[j] !== 'undefined' ? extend[j] : j);
                    });
                    return result.join(',');
                }
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

            }
        }
    };
    return Controller;
});
